package com.maint.m

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException

import com.maint.m.utils.BuildConfig

import retrofit2.Call
import retrofit2.http.*

import okhttp3.logging.HttpLoggingInterceptor


object NetworkUtils {

    private const val BASE_URL = BuildConfig.APP_BASE_URL // 替换为你的 API 基础 URL

    // OkHttpClient 配置，用于添加拦截器（如 token 校验）
    private val httpClient = OkHttpClient.Builder()
        .addInterceptor(TokenInterceptor())
        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        .addInterceptor(HttpLoggingInterceptor().apply {
            level = HttpLoggingInterceptor.Level.BODY
        })
        .build()

    // Retrofit 实例
    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(httpClient)
        .addConverterFactory(GsonConverterFactory.create())  // 使用自定义的 Gson 实例
        .build()

    // 获取 Retrofit 的服务接口
    fun <T> createService(serviceClass: Class<T>): T {
        return retrofit.create(serviceClass)
    }

    // Token 拦截器，用于添加 token 到请求头
    private class TokenInterceptor : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val originalRequest: Request = chain.request()

            // 获取当前应使用的 token（动态 or 默认）
            val authHeader = TokenManager.getAuthHeader()

            val requestWithToken = originalRequest.newBuilder()
                .header("token", authHeader) // 自动带 token
                .build()

            return chain.proceed(requestWithToken)
        }
    }
}

// 定义一个通用的接口
interface ApiService {
    @GET
    fun get(@Url url: String, @QueryMap params: Map<String, String>? = null): Call<String>

    @POST
    fun post(@Url url: String, @Body body: Any? = null): Call<ResponseBody>

    @PUT
    fun put(@Url url: String, @Body body: Any? = null): Call<String>

    @DELETE
    fun delete(@Url url: String): Call<String>
}

// 封装通用的请求方法
fun makeRequest(
    method: String,
    url: String,
    params: Map<String, String>? = null,
    body: Any? = null
): Call<String> {
    val service = NetworkUtils.createService(ApiService::class.java)

    return when (method.lowercase()) {
        "get" -> service.get(url, params)
        "post" -> throw IllegalArgumentException("POST method now returns ResponseBody, use ApiService directly")
        "put" -> service.put(url, body)
        "delete" -> service.delete(url)
        else -> throw IllegalArgumentException("Unsupported HTTP method: $method")
    }
}